import React, { useState, useRef, useEffect } from 'react';
import { Button, Popconfirm, FormInstance, Input } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getComplainList, closeComplain, batchCloseComplain } from '@/services/shop/api';
import TableHint from '@/components/TableHint/Index';
import { history } from 'umi';
import { MsgType, showMsg, formatDate, isExits, isSupportSticky } from '@/utils/utils';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';

const Index: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [ids, setIds] = useState<string[]>([]);
  const formRef = useRef<FormInstance>();
  const [visbile, setVisible] = useState<boolean>(false);
  const [batchCloseVisble, setBatchCloasVisible] = useState<boolean>(false);
  const [batchCloseLoading, setBatchCloasLoading] = useState<boolean>(false);

  const [line, setLine] = useState<number>(-1);

  const [totalNum, setTotalNum] = useState<number>(0)

  // 查看最新消息接口参数
  const [newsParams, setNewsParams] = useState<any>({});

  // 按表单筛选项查询
  const forFormSearch = () => {
    setNewsParams({});
    formRef.current?.submit();
  }

  const columns: ProColumns<SHOPAPI.ShopComplaint>[] = [
    {
      title: '订单编号',
      dataIndex: 'order_id',
      width: 150,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Input className='mySearch' onPressEnter={forFormSearch} style={{ width: '100%' }} placeholder="输入订单编号" />
        );
      },
    },
    {
      title: '用户账号',
      dataIndex: 'user_name',
      width: 120,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Input className='mySearch' onPressEnter={forFormSearch} style={{ width: '100%' }} placeholder="输入用户账号" />
        );
      },
    },
    {
      title: '投诉日期',
      dataIndex: 'create_date',
      valueType: 'date',
      hideInTable: true
    },
    {
      title: '投诉问题',
      dataIndex: 'problem',
      width: 200,
      search: false
    },
    {
      title: '最后一次回复',
      dataIndex: 'last_reply',
      width: 200,
      search: false
    },
    {
      title: '处理状态',
      dataIndex: 'status',
      valueType: 'select',
      width: 70,
      valueEnum: {
        U: '待处理',
        H: '处理中',
        C: '已关闭'
      }
    },
    {
      title: '是否有最新客户消息',
      dataIndex: 'new_user_news',
      valueType: 'select',
      width: 160,
      valueEnum: {
        1: '是',
        0: '否'
      }
    },
    {
      title: '最后一次处理时间',
      dataIndex: 'last_deal_time',
      search: false,
      width: 170,
    },
    {
      title: '操作',
      align: 'center',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      valueType: 'option',
      width: 150,
      render: (_, record, index) => [
        isExits('600612002') &&
        <a key="view" 
          onClick={() => {
            history.push({
              pathname: '/shop/complaint/detail',
              query: {
                complain_id: record.complain_id,
                order_id: record.order_id
              }
            })
          }}>查看</a>,

        record.status !== 'C' && <PermissionControl action_id="600612003">
          <Popconfirm 
            key="close"
            placement="topRight"
            title="关闭后无法再回复此问题，是否继续？"
            visible={visbile && line === index}
            onVisibleChange={setVisible}
            onConfirm={async () => {
              try {
                setVisible(true);
                await closeComplain(Object.assign({}, record, { status: 'C' }));
                showMsg('问题已关闭', MsgType.SUCCESS);
                actionRef.current?.reload();
                setVisible(false);
                setLine(-1);
              } catch (error) {
                showMsg(error?.data?.errmsg);
              }
            }}
            onCancel={() => {
              setVisible(false);
              setLine(-1);
            }}
            okText="确认关闭"
            cancelText="再想想">
            <a onClick={() => {
              setVisible(true);
              setLine(index);
            }}>关闭</a>
          </Popconfirm>
        </PermissionControl>
      ]
    }
  ];

  /**
   * 批量关闭问题
   * @returns 
   */
  const handleBatchClose = async () => {
    try {
      setBatchCloasLoading(true);
      await batchCloseComplain(ids);
      showMsg('问题已关闭', MsgType.SUCCESS);
      setIds([]);
      actionRef.current?.clearSelected?.();
      actionRef.current?.reload();
      setBatchCloasLoading(false);
    } catch (error) {
      setBatchCloasLoading(false);
     showMsg(error?.data?.errmsg);
    }
  }

  const onRowChange = (selectedRowKeys: React.Key[], selectedRows: SHOPAPI.ShopComplaint[]) => {
    if (!selectedRows.length) {
      setIds([]);
      return
    }
    const rows = selectedRows.map(item => {
      return item.complain_id;
    });
    setIds(rows as string[]);
  }

  useEffect(() => {
    formRef.current?.setFieldsValue({
      status: 'U'
    })
    formRef.current?.submit();
  }, [])

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<SHOPAPI.ShopComplaint, SHOPAPI.ShopComplaint & COMMON.PageParams>
        actionRef={actionRef}
        formRef={formRef}
        bordered
        className="custom-table"
        manualRequest={true}
        rowKey="complain_id"
        search={{
          span: 6,
          labelWidth: 140,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            return [<PermissionControl key="search" action_id="600612001">
              <Button type="primary" onClick={() => {
                forFormSearch();
              }}>查询</Button>
            </PermissionControl>];
          }
        }}
        request={async (params) => {
          try {
            if (params.create_date) {
              params.create_date = formatDate(params.create_date, 'YYYYMMDD');
            }

            if (newsParams.new_user_news) {
              params = {
                current: params.current,
                pageSize: params.pageSize,
                new_user_news: newsParams.new_user_news
              }
            }
            const data: SHOPAPI.ShopComplaintList = await getComplainList(params);
            setTotalNum(data.complain_todo_count)
           
            return {
              data: data.complain_list.record_list,
              success: true,
              total: data.complain_list.sum_record_num
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }}
        columns={columns}

        rowSelection={{
          columnWidth: 40,
          onChange: onRowChange,
          getCheckboxProps: (record) => {
            return {
              disabled: record.status === 'C'
            }
          }
        }}
        options={false}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'add',
                label: <PermissionControl action_id="600612004">
                    <Popconfirm  
                      visible={batchCloseVisble}
                      disabled={!ids.length}
                      title="关闭后无法再回复此问题，是否继续？"
                      onConfirm={handleBatchClose}
                      onVisibleChange={setBatchCloasVisible}
                      okButtonProps={{
                        loading: batchCloseLoading
                      }}
                      okText="确认关闭"
                      cancelText="再想想">
                        <Button onClick={() => {
                          setBatchCloasVisible(true);
                        }} disabled={!ids.length} type="primary">批量关闭投诉</Button>
                    </Popconfirm>
                </PermissionControl> 
              }
            ]
          }
        }}
        pagination={{
          showQuickJumper: true
        }}
        scroll={{
          x: 1000
        }}
        toolBarRender={() => [<div>
          { totalNum > 0 && <TableHint 
            text={<div>有 <span style={{color: '#F2232C', fontWeight: 'bold'}}>{totalNum}</span> 条最新消息等待处理。</div>} 
            onAction={() => {
              setNewsParams({
                new_user_news: '1'
              });
              formRef.current?.submit()
            }}
            showAction/>}
        </div>]
      }
      />
    </PageContainer>
  );
};

export default Index;
